package behavior.ObserverPattern.introduce.demo;

import java.util.ArrayList;
import java.util.List;

/**
 * 观察者模式实现
 * */
public class ObserPattern {
    public static void main(String[] args) {
        Subject subject = new Subject();
        Observer binaryObserver = new BinaryObserver(subject);
        Observer hexaObserver = new HexaObserver(subject);
        Observer observer = new OctalObserver(subject);
        subject.setState(1);
        subject.setState(10);
        subject.setState(100);
    }
}

/**
 * 观察者抽象类
 * */
abstract class Observer{

    protected Subject subject;

    public abstract void update(int pam);
}

/**
 * Oberver 实现类 BinaryObserver
 *
 * */
class BinaryObserver extends Observer{

    public BinaryObserver(Subject pam){
        this.subject = pam;
        pam.attach(this);
    }

    @Override
    public void update(int pam) {
        System.out.println("BinaryString = " + Integer.toBinaryString(pam));
    }
}

/**
 * Oberver 实现类 HexaObserver
 *
 * */
class HexaObserver extends Observer{

    public HexaObserver(Subject pam){
        this.subject = pam;
        pam.attach(this);
    }

    @Override
    public void update(int pam) {
        System.out.println("HexString = " + Integer.toHexString(pam));
    }
}
/**
 * Oberver 实现类 OctalObserver
 *
 * */
class OctalObserver extends Observer{

    public OctalObserver(Subject pam){
        this.subject = pam;
        pam.attach(this);
    }

    @Override
    public void update(int pam) {
        System.out.println("OctalString = " + Integer.toOctalString(pam));
    }
}


/**
 * 被观察者类
 * */
class Subject{
    List<Observer> observers = new ArrayList<>();
    /**
     * 被观察者状态
     * */
    int state;
    public int getState(){
        return this.state;
    }
    public void setState(int pam){
        this.state = pam;
        this.advice();
    }

    /**
     * 绑定观察者
     * */
    public void attach(Observer pam){
        this.observers.add(pam);
    }

    /**
     * 解除绑定
     * */
    public void remveOberver(Observer pam){
        this.observers.remove(pam);
    }

    /**
     * 通知观察者状态变化
     * */
    public void advice(){
        this.observers.stream().forEach((item)->{
            item.update(this.state);
        });
    }
}

